let lockCount = 0 //计数器
let oldScrollData = '' //记录旧的滚动数据

/** 锁定body滚动 */
function lockBodyScroll() {
    if (lockCount === 0) {
        oldScrollData = document.body.style.overflow
        document.body.style.overflow = 'hidden'
    }
    lockCount++
}

/** 解锁body滚动 */
function unlockBodyScroll() {
    lockCount--
    if (lockCount === 0) {
        document.body.style.overflow = oldScrollData
    }
}



/** header-search class */
class HeaderSearch {
    searchWrap = null; //父级容器
    searchForm = null; //表单
    searchInput = null; //输入框
    searchBtn = null; //搜索按钮
    searchHistory = null; //搜索历史
    blurTimer = null; //延时器

    constructor() {
        this.searchWrap = document.querySelector(".header_search_wrap");
        this.searchForm = document.querySelector(".header_search_form");
        this.searchInput = document.querySelector(".header_search_input");
        this.searchBtn = document.querySelector(".header_search_btn");

        // this.searchHistory = new SearchHistory({
        //     wrapClass: ".search_history",
        //     listClass: ".search_history_list",
        //     clearBtnClass: ".search_history_clear_btn",
        //     closeBlacklist: [this.searchWrap, document.querySelector(".mobile-search")],
        //     onListClick: this.onListClick.bind(this)
        // });

        this.inputClick = this.inputClick.bind(this);
        this.inputBlur = this.inputBlur.bind(this);

        //绑定事件
        this.searchInput.addEventListener("click", this.inputClick);
        this.searchInput.addEventListener("blur", this.inputBlur);
        //阻止回车按下时提交表单
        this.searchForm.addEventListener("keydown", (event) => {
            if (event.key.toLocaleLowerCase() === "enter") {
                event.preventDefault();
            }
        });
        //回车回位时触发搜索
        this.searchForm.addEventListener("keyup", (event) => {
            if (event.key.toLocaleLowerCase() === "enter") {
                this.onSubmit();
            }
        });
        //搜索按钮点击事件
        this.searchBtn.addEventListener("click", () => {
            if (this.blurTimer) {
                clearTimeout(this.blurTimer);
                this.blurTimer = null;
            }
            this.onSubmit();
        });
    }

    /** input点击事件 */
    inputClick() {
        //如果开启了移动端搜索,则不处理open展开
        // if (!dataStore.getEnableMobileSearch) {
        // }
        this.searchWrap.classList.add("open_search");
        // this.searchHistory.show();
    }

    /** input 离开事件 */
    inputBlur() {
        //如果开启了移动端搜索,则不处理open展开
        // if (dataStore.getEnableMobileSearch) return;
        this.blurTimer = setTimeout(() => {
            this.searchWrap.classList.remove("open_search");
        }, 200);
    }

    /** 历史记录点击回调 */
    onListClick(val) {
        this.searchInput.setAttribute("value", val);
        this.searchHistory.hide();
        this.searchHistory.addHistory(val);
        this.searchForm.submit();
    }

    /** 表单提交事件 */
    onSubmit() {
        const value = this.searchInput.value;
        if (value.trim() === "") return; //空值不提交
        this.searchHistory.addHistory(value);
        this.searchForm.submit();
    }
}
new HeaderSearch();


/** login-dialog class */
class LoginDialog {
    qrCodeImg = null; //二维码容器
    loginBtn = null; //登录按钮
    dialog = null; //弹窗容器
    closeBtn = null; //关闭按钮
    mask = null; //遮罩层
    dialogContent = null; //弹窗内容
    articleBtn = null; //写文章按钮
    loginForm = null; // 登录 Form
    loginList = null; // login 集合
    constructor() {
        this.loginBtn = document.querySelector(".header-login-btn");
        if (!this.loginBtn) return;
        this.dialog = document.querySelector(".login-dialog");
        this.qrCodeImg = document.querySelector(".login-dialog-qrcode-img");
        this.closeBtn = document.querySelector(".login-dialog-close");
        this.mask = document.querySelector(".login-dialog-mask");
        this.dialogContent = document.querySelector(".login-dialog-content");
        this.articleBtn = document.querySelector(".header_article_btn");
        this.loginForm = document.querySelector(".login-dialog-form");

        //二维码
        // this.createQrCode();
        //绑定事件
        this.loginBtn.addEventListener("click", this.onClickLogin.bind(this));
        this.closeBtn && this.closeBtn.addEventListener("click", this.onClickClose.bind(this));
        this.mask && this.mask.addEventListener("click", this.onClickClose.bind(this));
        this.loginForm?.addEventListener("submit", this.onLoginUser.bind(this));

        this.loginList = document.querySelectorAll(".login");
        this.loginList = Array.from(this.loginList);

        this.loginList.forEach((ele) => {
            ele.addEventListener("click", this.onClickLogin.bind(this));
        });

        // if (this.articleBtn) {
        // 	this.articleBtn.addEventListener("click", this.writeArtice.bind(this));
        // }
        //协议按钮
        const protocolBtn = Array.from(document.querySelectorAll(".login-dialog-footer .login-dialog-link"));
        protocolBtn.forEach((btn) => {
            btn.addEventListener("click", this.onProtocolBtnClick);
        });
    }

    /** 生成二维码并丢入html中 */
    // private createQrCode() {
    // 	QRCode.toDataURL("https://s1.ax1x.com/2023/03/17/ppGkaMd.png", { margin: 1 })
    // 		.then((url) => {
    // 			this.qrCodeImg?.setAttribute("src", url);
    // 		})
    // 		.catch((error) => {
    // 			console.error("二维码生成失败", error);
    // 		});
    // }

    writeArtice() {
        window.location.href = "/admin/article.php?action=write";
    }
    /** 登录按钮点击事件 */
    onClickLogin(e) {
        e.preventDefault();
        if (!this.dialog) return;
        this.dialog.classList.add("visible");
        getComputedStyle(this.dialog).display;
        this.mask?.classList.add("visible");
        this.dialogContent?.classList.add("visible");
        lockBodyScroll();
    }

    async onLoginUser(e) {
        let _this = this;
        try {
            e.preventDefault();
            let data = getFormData(this.loginForm);
            console.log(data);
            let user = data?.username;
            let pw = data?.password;

            const loginRes = await login({ resp: "json", user, pw });
            if (loginRes.code === 0) {
                toast.success({
                    text: "正在登录...",
                    callback() {
                        _this.onClickClose();
                        window.location.reload();
                    }
                });
            }
        } catch (error) { }
    }

    /** 关闭弹窗事件 */
    onClickClose() {
        if (!this.dialog || !this.dialogContent) return;
        this.dialogContent.addEventListener(
            "transitionend",
            () => {
                this.dialog?.classList.remove("visible");
                this.dialogContent?.classList.remove("hidden");
                this.dialogContent?.classList.remove("visible");
                unlockBodyScroll();
            },
            { once: true }
        );

        getComputedStyle(this.dialog).display;

        this.mask?.classList.remove("visible");
        this.dialogContent.classList.add("hidden");
    }

    /** 协议按钮事件 */
    onProtocolBtnClick = () => { };
}
new LoginDialog();